//
//  DestTabBarViewController.m
//  TravelEveryDay
//
//  Created by dlios on 15/10/15.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "DestTabBarViewController.h"
#import "BaseHeader.h"
#import "DestTabBarModel.h"
#import "DestTabBarSectionModel.h"
#import "DestTabBarTwoImageTableViewCell.h"
#import "DestTabBarFourImageTableViewCell.h"
#import "DestMoreCountryViewController.h"
#import "DestFirstCellInfoViewController.h"
#import "DestOtherCellInfoViewController.h"
#import "GiFHUD.h"
@interface DestTabBarViewController ()<UITableViewDelegate,UITableViewDataSource,destTabBarCollectionViewCellDelegate,destTabBarCollectionViewTwoImageCellDelegate>
@property(strong,nonatomic)UITableView *destTabelView;//目的地的页面的tabelView
@property(strong,nonatomic)NSMutableArray *destTabBarSectionArray; // 放装model数组的数组
@property(strong,nonatomic)NSMutableArray *destTabBarModelArray;//放目的地首页的model数组;
@property(strong,nonatomic)NSMutableArray *destTabelViewSectionTitleArray;//放目的地的section描述的数组
@end

@implementation DestTabBarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:251/255. green:246/255. blue:233/255. alpha:1];
    //    self.automaticallyAdjustsScrollViewInsets  = NO;//取消某些控件自适应;
    //数组初始化
    //    _destTabBarModelArray = [[NSMutableArray alloc]init];
    self.title = @"旅游胜地";
    _destTabBarSectionArray = [[NSMutableArray alloc]init];
    _destTabelViewSectionTitleArray  = [[NSMutableArray alloc]init];
    [self createDsetTableView];//创建tabelView
    //先从缓存拿数据  在请求数据 刷新数据
    _destTabelViewSectionTitleArray = [NSMutableArray arrayWithArray:[self getDestDataFormSandBox:@"sectionTitle"]];
    _destTabBarSectionArray = [NSMutableArray arrayWithArray:[self getDestDataFormSandBox:@"sectionRow"]];
    if (_destTabBarSectionArray.count == 0) {
        NSLog(@"第一次进入没有缓存");
    }else{
        
        [_destTabelView reloadData];
    }
    [self getDestData];
    
}
#pragma mark - 创建目的地的 tabelView
- (void)createDsetTableView {
    _destTabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT -44 ) style:UITableViewStyleGrouped];
    _destTabelView.backgroundColor = [UIColor colorWithRed:251/255. green:246/255. blue:233/255. alpha:1];
    _destTabelView.delegate = self;
    _destTabelView.dataSource = self;
    [_destTabelView setSeparatorStyle:UITableViewCellSeparatorStyleNone];//去掉tabelView的线
    [self.view addSubview:_destTabelView];
    
}
#pragma mark -  目的地的首页数据请求 代码
///改善了 首页不存在刷新加载 没必要带个字符串的方法
- (void)getDestData {
    ///皮卡丘
    
    
    [DestAFNDataBlock string:@"http://api.breadtrip.com/destination/v3/" AFNData:^(id block) {
        NSMutableDictionary *jsonDic = block;
        NSMutableArray *elementsArray = [jsonDic objectForKey:@"elements"];
        NSInteger cellIndex = 0;
        for (NSMutableDictionary *elementsDic in elementsArray) {
            DestTabBarSectionModel *sectionModel = [DestTabBarSectionModel modelWithDictionary:elementsDic];
            //给model添加到sectiontitle的数据里面
            [_destTabelViewSectionTitleArray addObject:sectionModel];
            NSMutableArray *dataArray = [elementsDic objectForKey:@"data"];
            //初始化装model的数组
            _destTabBarModelArray = [[NSMutableArray alloc]init];
            for (NSMutableDictionary *dataDic in dataArray) {
                DestTabBarModel *model = [DestTabBarModel modelWithDictionary:dataDic];
                [_destTabBarModelArray addObject:model];
                
            }
            
            [_destTabBarSectionArray addObject:_destTabBarModelArray];
            cellIndex ++;
        }
        
        //存数据
        [self setData:_destTabelViewSectionTitleArray FileName:@"sectionTitle"];
        [self setData:_destTabBarSectionArray FileName:@"sectionRow"];
        
        //存入沙盒
        
        // [[NSUserDefaults standardUserDefaults]setObject:_destTabBarSectionArray forKey:@"desthuancun"];
        
        
        //        [self setData:_destTabBarSectionArray];

        [_destTabelView reloadData];//刷新;
    } AFNData1:^(id block) {
        [GiFHUD dismiss];
        //        _destTabelViewSectionTitleArray = [NSMutableArray arrayWithArray:[self getDestDataFormSandBox:@"sectionTitle"]];
        //        _destTabBarSectionArray = [NSMutableArray arrayWithArray:[self getDestDataFormSandBox:@"sectionRow"]];
        //        [_destTabelView reloadData];
        //_destTabBarSectionArray =[[NSUserDefaults standardUserDefaults]objectForKey:@"huancun"];
        
        //        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"当前网络不好" preferredStyle:UIAlertControllerStyleAlert];
        //        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //
        //        }];
        
        //   [alertController addAction:action];
        //  [self presentViewController:alertController animated:YES completion:nil];
        
        
    }];
}
#pragma mark - tabelView的代理方法 : 返回section的个数
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return _destTabBarSectionArray.count;
    // return _destTabelViewSectionTitleArray.count;
}
#pragma mark - tabelView的代理方法 : 返回个数
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  1;
}
#pragma mark - tabelView代理方法 : 返回高度
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *destModelArr = [_destTabBarSectionArray objectAtIndex:indexPath.section];
    
    if (destModelArr.count == 4) {
        return (SCREEN_WIDTH +5*HEIGHT);
    } else {
        
        return ((SCREEN_WIDTH -25 *WIDTH)/2 +25 *WIDTH);
    }
}

#pragma mark - tableView的代理方法 : 返回section自定义View
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    DestTabBarSectionModel *sectionModel =[_destTabelViewSectionTitleArray objectAtIndex:section];
    UIView *sectionCustomView = [self createSection:section];
    //根据数据中more的bool值来判断section能否被点击
    if (sectionModel.more) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = sectionCustomView.frame;
        button.tag = section;
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *rightLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-50*WIDTH, 10*HEIGHT, 40*WIDTH, 30*HEIGHT)];
        rightLabel.text = @">";
        [sectionCustomView addSubview:rightLabel];
        [sectionCustomView addSubview:button];
    }
    return sectionCustomView;
}
#pragma mark - tableView代理方法 返回脚的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.000001;
}
#pragma mark - tableViewsection代理方法 :返回section高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50.*HEIGHT;
}
#pragma mark - tabelView的代理方法 : 返回cell种类
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //写出model为下面赋值 做准备
    NSMutableArray *destModelArr = [_destTabBarSectionArray objectAtIndex:indexPath.section];
    //判断数组个数 来返回cell形式
    if (destModelArr.count == 4) {
        static NSString *cellId= @"DestTabBarFourImageTableViewCell";
        DestTabBarFourImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[DestTabBarFourImageTableViewCell alloc]initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:cellId];
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
        cell.destSectionModelArray = [NSMutableArray arrayWithArray:destModelArr];//传值属性
        cell.collectionDelegate = self;//签署代理
        return cell;
    }else{
        static NSString *TwoCellId = @"DestTabBarTwoImageTableViewCell";
        DestTabBarTwoImageTableViewCell *TwoCell = [tableView dequeueReusableCellWithIdentifier:TwoCellId];
        if (!TwoCell) {
            TwoCell = [[DestTabBarTwoImageTableViewCell alloc]initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:TwoCellId];
        }
        [TwoCell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
        TwoCell.destSectionModelArray = destModelArr;//给cell赋值
        TwoCell.delegate = self;///签代理
        return TwoCell;
    }
}

#pragma mark - 创建伪造的section的空间的方法
-(UIView *)createSection :(NSInteger)section {
    DestTabBarSectionModel *sectionModel =[_destTabelViewSectionTitleArray objectAtIndex:section];
    UIView *sectionCustomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30*HEIGHT)];
    UILabel *sectionLabel = [[UILabel alloc]initWithFrame:CGRectMake(10 *WIDTH, 15 *HEIGHT, 10*WIDTH, 20 *HEIGHT)];
    sectionLabel.layer.cornerRadius = 5 *HEIGHT;
    sectionLabel.layer.masksToBounds = YES;
    sectionLabel.backgroundColor = [UIColor colorWithRed:62/255 green:176/255. blue:193/255. alpha:1];
    UILabel *titleLable = [[UILabel alloc]initWithFrame:CGRectMake(25*WIDTH,10 *HEIGHT, SCREEN_WIDTH - 100, 30 *HEIGHT)];
    titleLable.text = sectionModel.title;
    [sectionCustomView addSubview:titleLable];
    [sectionCustomView addSubview:sectionLabel];
    return sectionCustomView;
}
#pragma mark - section上button的点击方法
- (void)buttonAction:(UIButton *)sender {
    DestTabBarSectionModel *sectionModel =[_destTabelViewSectionTitleArray objectAtIndex:sender.tag];
    //根据数据串参数进入二级页面
    DestMoreCountryViewController *destMoreCountry = [[DestMoreCountryViewController alloc]init];
    destMoreCountry.index = sectionModel.index;
    [self.navigationController pushViewController:destMoreCountry animated:YES];
}
#pragma mark - 签署collecitionView四个图的代理方法
- (void)collectionDidselected:(NSNumber *)myId cellIndex:(NSInteger)cellIndex myType:(NSNumber *)type {
    ///判断传回来的值 来决定push到哪个页面 同时传值下一页面请求数据
    if (type.integerValue == 5) {
        DestFirstCellInfoViewController *firstCellInfo = [[DestFirstCellInfoViewController alloc]init];
        firstCellInfo.MyId = myId;
        firstCellInfo.type = type;
        [self.navigationController pushViewController:firstCellInfo animated:YES];
    }else{
        DestOtherCellInfoViewController *otherCellInfo = [[DestOtherCellInfoViewController alloc]init];
        otherCellInfo.type = type;
        otherCellInfo.MyId = myId;
        [self.navigationController pushViewController:otherCellInfo animated:YES];
    }
}
#pragma mark  - 签署collecitionView两个个图的代理方法
- (void)collectionTwoDidselected:(NSNumber *)TwoMyId TwocellIndex:(NSInteger)TwocellIndex TwoMyType:(NSNumber *)myType {
    ///判断传回来的值 来决定push到哪个页面 同时传值下一页面请求数据
    if (myType.integerValue ==5) {
        DestFirstCellInfoViewController *firstCellInfo = [[DestFirstCellInfoViewController alloc]init];
        firstCellInfo.MyId = TwoMyId;
        firstCellInfo.type = myType;
        [self.navigationController pushViewController:firstCellInfo animated:YES];
    }else{
        DestOtherCellInfoViewController *otherCellInfo = [[DestOtherCellInfoViewController alloc]init];
        otherCellInfo.MyId = TwoMyId;//下级页面网址请求拼接参数
        otherCellInfo.type = myType;
        [self.navigationController pushViewController:otherCellInfo animated:YES];
    }
    
}
#pragma mark - 缓存的方法 用归档
- (void)setData: (NSMutableArray *)fileArray  FileName:(NSString *)fielName{
    NSString *cachesString = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    NSString *pathString = [cachesString stringByAppendingString:[NSString stringWithFormat:@"/%@",fielName]];
    ///归档文件写入
    BOOL sucsess = [NSKeyedArchiver archiveRootObject:fileArray toFile:pathString];
    if (sucsess) {
        NSLog(@"成功");
    }else{
        NSLog(@"失败");
    }
}
#pragma mark - 反归档 无网 读取文件
- (NSArray *)getDestDataFormSandBox:(NSString *)fileName {
    NSString *cachesString = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    NSString *pathString = [cachesString stringByAppendingString:[NSString stringWithFormat:@"/%@",fileName]];
    NSArray *destArray = [NSKeyedUnarchiver unarchiveObjectWithFile:pathString];
    return destArray;
}
#pragma mark - 视图即将出现
- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.alpha = 1.0f;
    self.tabBarController.tabBar.hidden = NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
